package com.pw.study.flink.state;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class keyStateList {
    public static void main(String[] args) {
        dealList();
    }

    private static void dealList() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        //输入数据
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop111", 9999).map(value -> {
            String[] line = value.split(",");
            return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));
        });

        //
        stream.keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    private ListState<Integer> listStateVc;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        listStateVc = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("listTop3", Types.INT));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        Integer vc = value.getVc();
                        listStateVc.add(vc);
                        List<Integer> list = StreamSupport.stream(listStateVc.get().spliterator(), true).collect(Collectors.toList());
                        //list.sort((o1, o2) -> o2.compareTo(o1));
                        list.sort(Comparator.reverseOrder());

                        if (list.size() > 3) {
                            list.remove(list.size() - 1);
                        }
                        out.collect("top3" + list);
                        listStateVc.update(list);
                    }
                }).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
